package br.com.iswe.gwt.ui.client;

import java.util.ArrayList;
import java.util.List;

public class ClientInfoContext {

	private static ClientInfoContext clientInfoContext;
	
	private static List<Listener<SessionInfo>> onChangeSessionInfoList = new ArrayList<Listener<SessionInfo>>();
	
	private SessionInfo sessionInfo;
	
	private ClientInfoContext(SessionInfo sessionInfo) {
		this.sessionInfo = sessionInfo;
	}

	public static void setClientInfoContext(SessionInfo sessionInfo){
		clientInfoContext = new ClientInfoContext(sessionInfo);
		//notifica todos os listeners que mudaram os dados de sessao do cliente
		fireOnChangeSessionInfo(sessionInfo);
	}
	
	public static void clearClientInfoContext(){
		if(clientInfoContext != null){
			clientInfoContext.sessionInfo.setUserId(null);
			clientInfoContext.sessionInfo.setUserNameToDisplay(null);
			clientInfoContext.sessionInfo.setListaPapeis(new ArrayList<String>());
			
			//dont clear the properties... therefore no security information should be stored inside the properties map
		
			//notifica todos os listeners que mudaram os dados de sessao do cliente
			fireOnChangeSessionInfo(clientInfoContext.sessionInfo);
	
		}
	}
	
	private static void fireOnChangeSessionInfo(SessionInfo sessionInfo) {
		//varre a lista de eventos onChangeSessionInfoList e dispara
		for (int i = 0; i < onChangeSessionInfoList.size(); i++) {
			Listener<SessionInfo> listener = onChangeSessionInfoList.get(i);
			listener.execute(sessionInfo);
		}
	}

	public static ClientInfoContext getClientInfoContext(){
		if( clientInfoContext == null ){
			clientInfoContext = new ClientInfoContext(new RequestInfo());
		}
		return clientInfoContext;
	}

	public static void addOnChangeSessionInfo(Listener<SessionInfo> listener){
		onChangeSessionInfoList.add(listener);
	}
	
	public SessionInfo getSessionInfo() {
		return sessionInfo;
	}
	public void setSessionInfo(SessionInfo sessionInfo) {
		this.sessionInfo = sessionInfo;
	}
}
